package com.project.zsxd.server.common.handler;

import com.project.zsxd.server.common.bean.Result;
import com.project.zsxd.server.common.enums.ResultEnum;
import com.project.zsxd.server.common.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理类
 * Created by kaler on 2020/3/27.
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result handlerException(HttpServletResponse response, Exception exception) {
        log.error("GlobalExceptionHandler.", exception);
        return new Result(ResultEnum.SYSTEM_ERROR, false, null);
    }

    /**
     * 捕捉系统异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(SystemException.class)
    public Result handleSystemException(SystemException exception) {
        log.error("handleSystemException.", exception);
        return new Result(exception);
    }

    /**
     * 捕捉shiro的异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ShiroException.class)
    public Result handleShiroException(ShiroException exception) {
        log.error("handleShiroException.", exception);
        return Result.fail(ResultEnum.USER_AUTHORIZATION_ERROR);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Result handleAuthenticationException(AuthenticationException exception) {
        log.error("handleAuthenticationException.", exception);
        return Result.fail(ResultEnum.USER_AUTHENTICATION_ERROR);
    }
}
